<template>
  <div class="list-table">
    <div v-if="this.$route.query.type === 'WB'" class="area-header">
      <span class="area-header-title">{{ $t('基金管理人') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.native.prevent>
      <el-form-item :label="$t('管理人全称')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('管理人全称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <!-- <el-form-item :label="$t('管理人简称')" prop="shortName">
        <el-input
          v-model="queryParams.shortName"
          :placeholder="$t('管理人简称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>-->
      <!-- <el-form-item :label="$t('管理人类型')" prop="type">
        <el-select v-model="queryParams.type" :placeholder="$t('管理人类型')" clearable>
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>-->
      <!-- <el-form-item :label="$t('机构类型')" prop="organizationType">
        <el-select v-model="queryParams.organizationType" :placeholder="$t('机构类型')" clearable>
          <el-option
            v-for="dict in organizationTypeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['fund:gpbase:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>

      <!--<el-button
         v-hasPermi="['fund:gpbase:edit']"
         type="primary"
         icon="el-icon-plus"
         size="mini"
         style="display: none"
         @click="historyData"
       >处理老数据</el-button>
     </el-col>-->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['fund:gpbase:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="gpBaseList" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('管理人全称')" align="center" prop="name">
        <template slot-scope="scope">
          <router-link
            target="_blank"
            :to="{path:'/fund/gpBase/gpBaseHome',query:{ id:scope.row.id, gpId: scope.row.id }}"
            class="link_a"
            @click.native="recorePath({ fromPath: $route.fullPath, path:'/fund/gpBase/gpBaseHome',query:{id:scope.row.id,gpId:scope.row.id}})"
          >{{ scope.row.name }}</router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('管理人简称')" align="center" prop="shortName" />
      <!-- <el-table-column :label="$t('管理人类型')" align="center" prop="type" :formatter="typeFormat" show-overflow-tooltip width="120" />-->
      <el-table-column :label="$t('成立时间')" align="center" prop="setDate" show-overflow-tooltip width="110">
        <template slot-scope="scope">
          <span>{{ scope.row.company ? parseTime(scope.row.company.setDate) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('是否为执行事务合伙人')" align="center" prop="isExecutivePartner" :formatter="isExecutivePartnerFormat" />
      <el-table-column :label="$t('是否为投资顾问')" align="center" prop="isInvestmentAdvisor" :formatter="isInvestmentAdvisorFormat" show-overflow-tooltip width="130" />
      <el-table-column :label="$t('机构组织形式')" align="center" prop="organizationForm" :formatter="organizationFormFormat" show-overflow-tooltip width="140" />
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.type === 'WB'"
            v-hasPermi="['fund:gpbase:edit']"
            size="small"
            type="text"
            icon="el-icon-link"
            @click="openAccount(scope.row)"
          >{{ $t('管理账号') }}</el-button>
          <el-button
            v-if="scope.row.type === 'WB'"
            v-hasPermi="['fund:gpbase:edit']"
            :disabled="scope.row.accountName === null || scope.row.accountName === ''"
            size="small"
            type="text"
            icon="el-icon-error"
            @click="delAccount(scope.row)"
          >{{ $t('注销账号') }}</el-button>
          <el-button
            v-hasPermi="['fund:gpbase:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['fund:gpbase:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改基金管理人对话框 -->
    <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" custom-class="dialogForm" append-to-body>
      <gpBaseForm ref="gpBaseForm" :bus-type="busType" />
    </el-dialog>

    <!-- 开通账号对话框 -->
    <el-dialog :title="accountTitle" :visible.sync="accountFormOpen" :close-on-click-modal="false" style="height: 530px;" width="30%" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <el-form ref="ruleForm" v-loading="accountLoading" :model="accountForm" status-icon :rules="rulesAccount" class="demo-ruleForm">
        <el-form-item :label="$t('登录名称')" prop="userName">
          <el-input v-model="accountForm.userName" :disabled="userDisable" :placeholder="$t('登录名称')" show-word-limit maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('登录密码')" prop="password">
          <el-input v-model="accountForm.password" type="password" autocomplete="off" :placeholder="$t('登录密码')" show-word-limit maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('确认密码')" prop="confirmPassword">
          <el-input v-model="accountForm.confirmPassword" type="password" autocomplete="off" :placeholder="$t('确认密码')" show-word-limit maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('填报类型')" prop="dataType">
          <el-radio-group v-model="accountForm.dataType">
            <el-radio label="TB">{{ $t('填报') }}</el-radio>
            <el-radio label="SB">{{ $t('申报') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-button type="primary" @click="submitAccount">{{ $t('提交') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { listGpBase, delGpBase, historyData } from '@/api/fund/gp/gpBase'
import {
  delBfAccount,
  getByGpId, saveAccountUser,
  verifyThatTheAccountExists
} from '@/api/bf/account/bfPortalAccount'
import gpBaseForm from './gpBaseForm.vue'

export default {
    components: {
        gpBaseForm
    },
  data() {
    var checkPassword = (rule, value, callback) => {
      const that = this.accountForm
      if (!value) {
        return callback(new Error(this.$t('必填信息')))
      } else if (that.password !== that.confirmPassword) {
        callback(new Error(this.$t('两次密码不一致!')))
      } else {
        callback()
      }
    }
    var checkUserName = (rule, value, callback) => {
      const that = this.accountForm
      if (!value) {
        return callback(new Error(this.$t('必填信息')))
      } else if (that.userName.length < 2) {
        callback(new Error(this.$t('登录名至少2位')))
      } else {
        if (!this.userDisable) {
          verifyThatTheAccountExists(this.accountForm.userName).then(response => {
            if (!this.loginNameDisable) {
              if (response.code === 200) {
                if (response.data) {
                  callback()
                } else {
                  callback(new Error(this.$t('账号已存在!')))
                }
              } else {
                callback(new Error(this.$t('发生未知错误!')))
              }
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      }
    }
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 基金管理人表格数据
          gpBaseList: [],
          // 弹出层标题
          title: '',
          busType: 'GP',
          // 是否显示弹出层
          formOpen: false,
        // 管理人类型字典
        typeOptions: [],
        // 是否完成基金业协会登记日期字典
        isConsortiumRegistryOptions: [],
        // 机构企业性质字典
        natureEnterpriseOptions: [],
        // 机构类型字典
        organizationTypeOptions: [],
        // 机构组织形式字典
        organizationFormOptions: [],
        // 是否为执行事务合伙人
        isExecutivePartnerOptions: [],
        // 是否为投资顾问
        isInvestmentAdvisorOptions: [],
          // 查询参数
          queryParams: {
              name: undefined,
              shortName: undefined,
              type: this.$route.query.type,
              organizationType: undefined,
              pageNum: 1,
              pageSize: 10
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
          },
        // 开通账号加载
        accountLoading: false,
        // 用户名是否可修改
        userDisable: false,
        // 开通账号表单
        accountForm: {
          gpId: '',
          userName: '',
          password: '',
          confirmPassword: ''
        },
        rulesAccount: {
          userName: [{ required: true, validator: checkUserName,	trigger: 'blur' }],
          password: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
          confirmPassword: [{ required: true, validator: checkPassword,	trigger: 'blur' }],
          dataType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
        },
        accountTitle: '',
        // 开通账号弹出层
        accountFormOpen: false
      }
  },
  created() {
      this.getList()
      this.getDicts('fund_manger_type').then(response => {
          this.typeOptions = response.data
      })
      this.getDicts('sys_yes_no').then(response => {
          this.isConsortiumRegistryOptions = response.data
          this.isExecutivePartnerOptions = response.data
          this.isInvestmentAdvisorOptions = response.data
      })
      this.getDicts('manager_enterprise_nature').then(response => {
          this.natureEnterpriseOptions = response.data
      })
      this.getDicts('manager_type').then(response => {
          this.organizationTypeOptions = response.data
      })
      this.getDicts('manager_organizational form').then(response => {
          this.organizationFormOptions = response.data
      })
  },
  methods: {
    /** 查询基金管理人列表 */
    getList() {
        this.loading = true
        if (this.$route.query.type === 'NB') {
          this.queryParams.busType = 'GP'
        }
        listGpBase(this.queryParams).then(response => {
            this.gpBaseList = response.rows
            this.total = response.total
            this.loading = false
        })
    },
    // 处理老数据
    historyData() {
      historyData().then(response => {
        console.log(response)
      })
    },
    // 管理人类型字典翻译
    typeFormat(row, column) {
      console.log(column)
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 是否完成基金业协会登记日期日期字典翻译
    isConsortiumRegistryFormat(row) {
      return this.selectDictLabel(this.isConsortiumRegistryOptions, row.isConsortiumRegistry)
    },
    // 是否为执行事务合伙人字典翻译
    isExecutivePartnerFormat(row) {
      return this.selectDictLabel(this.isExecutivePartnerOptions, row.isExecutivePartner)
    },
    // 是否为投资顾问
    isInvestmentAdvisorFormat(row) {
      return this.selectDictLabel(this.isInvestmentAdvisorOptions, row.isInvestmentAdvisor)
    },
    // 机构组织形式字典翻译
    organizationFormFormat(row) {
      return this.selectDictLabel(this.organizationFormOptions, row.organizationForm)
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            company: {},
            type: '0',
            isConsortiumRegistry: '0'
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.title = this.$t('基金管理人')
        this.$nextTick(() => {
            this.$refs.gpBaseForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.title = this.$t('基金管理人')
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.gpBaseForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delGpBase(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
      this.downLoadExcel('/base/gpBase/gpExport', this.queryParams)
    },
    // 开通企业填报账号
    openAccount(row) {
      this.accountForm.gpId = row.id
      // this.accountForm.userName = row.name
      this.accountForm.gpName = row.name
      // this.accountForm.dataType = 'TB'
      this.accountFormOpen = true
      this.accountLoading = true
      getByGpId(row.id).then(response => {
        if (response.code === 200) {
          if (response.data !== null) {
            this.accountForm = response.data
            this.accountForm.password = ''
            this.userDisable = true
            this.accountTitle = this.$t('修改账户')
          } else {
            this.userDisable = false
            this.accountTitle = this.$t('开通账户')
          }
        }
        this.accountLoading = false
      })
    },
    // 开通账户
    submitAccount() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.openAnAccountLoading = true
          saveAccountUser(this.accountForm).then(response => {
            if (response.code === 200) {
              this.accountFormOpen = false
              this.msgSuccess(this.$t('开通成功!'))
            } else {
              this.msgError(this.$t('保存异常'))
            }
            this.accountLoading = false
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除账户
    delAccount(row) {
      this.$confirm(this.$t('是否注销账号?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delBfAccount(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('操作成功!'))
      })
    }
  }
}
</script>
